﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Trade.DBUtility;
using Trade.DBUtility.DataTableName;
using TradeWeb.Models;
using System.Web.Script.Serialization;
using System.IO;
using System.Dynamic;
using Newtonsoft.Json.Linq;
using System.Collections;
namespace TradeWeb.Controllers
{
    public class PDController : Controller
    {
        //
        // GET: /PD/

        public ActionResult Index()
        {
            return View();
        }
        public string GetXLCodeInfo(string BarCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            DataSet ds = new DataSet();
            //string SQL = "select InvCode cInvCode,cInvName,OrderSerialID XLCode,cWhCode,cBatchNo cBatch,iSNState from t_dispatch_serialno a " +
            //"left join " + Common.GetdatabaseName("") + ".dbo.ST_SNState b on OrderSerialID=cInvSN where OrderSerialID='" + BarCode + "'";
            string SQL = "select  a.cInvCode,cInvName,a.cInvSN XLCode,a.cWhCode, cBatch,iSNState from " + Common.GetdatabaseName("") + ".dbo.ST_SNState a " +
               " left join " + Common.GetdatabaseName("") + ".dbo.Inventory i on i.cinvcode = a.cInvCode where cInvSN='" + BarCode + "'";
            try
            {
                ds = CustomizableDesignBLL.GetData(SQL);
            }
            catch (Exception ex)
            {
                damResult.message = "获取信息报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            List<dynamic> varList = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                foreach (DataRowView drv in ds.Tables[0].DefaultView)
                {
                    var item = Trade.DBUtility.ExtendObject.AutoMap(drv.Row);
                    varList.Add(item);
                }
                damResult.success = true;
                damResult.data = varList;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            jsonResult = "{\"success\":false   ,\"message\":\"此序列号不存在\"}";
            return jsonResult;

        }
        #region 获取最大流水号
        public int GetMaxLs(string Info, string TableName, string ColumnName, int len)
        {
            DataSet ds = new DataSet();
            List<DataTableName> dtnList = new List<DataTableName>();
            DataTableName dtn = new DataTableName();
            dtn.strSelectSQL = "SELECT MAX(SubString(" + ColumnName + ",LEN(" + ColumnName + ")-" + (len - 1) + "," + len + ")) MaxCode FROM " + TableName + " WHERE " + ColumnName + " like '" + Info + "%'";
            dtn.strTableName = "LS";
            dtnList.Add(dtn);
            try
            {
                ds = CustomizableDesignBLL.GetData(dtnList, false);
            }
            catch (Exception ex)
            {
                return 1;
            }
            List<dynamic> varList = new List<dynamic>();
            if (ds.Tables[0].DefaultView.Count > 0 && !string.IsNullOrEmpty(ds.Tables[0].DefaultView[0][0].ToString()))
            {
                return int.Parse(ds.Tables[0].DefaultView[0][0].ToString()) + 1;

            }
            return 1;

        }
        #endregion
        public string SavePDList(string DetailList, string userCode, string cWhCode)
        {
            string jsonResult = string.Empty;
            //构造反馈对象
            dynamic damResult = new ExpandoObject();
            damResult.success = false;
            damResult.message = "获取失败";
            string strPKValue = "";
            //测试直接JSON转换数据集的 这个是可以做的，但是不是需要现在做的。因为这个是整个框架都要改了。没那个时间
            //DataSet dstest = JsonConvert.DeserializeObject<DataSet>(strDsData);
            string strTableName = "T_PD";
            string strTableDetail = "T_PDProduct";
            //是否新增
            bool bisAdd = false;
            //先获取数据库数据，如果没有数据就新增
            List<DataTableName> dtnGetDataList = new List<DataTableName>();
            DataSet dsGetData = new DataSet();
            DataTableName dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableName + " where 1=0";
            dtnGetData.strTableName = strTableName;
            dtnGetDataList.Add(dtnGetData);
            //
            dtnGetData = new DataTableName();
            dtnGetData.strSelectSQL = "Select * from " + strTableDetail + " where 1=0 ";
            dtnGetData.strTableName = strTableDetail;
            dtnGetDataList.Add(dtnGetData);
            //
            try
            {
                dsGetData = CustomizableDesignBLL.GetData(dtnGetDataList, true);
            }
            catch (Exception ex)
            {
                damResult.message = "获取模块数据表结构失败:" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            //
            #region 主表部分
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            dsGetData.Tables[0].Rows.Add(dsGetData.Tables[0].NewRow());
            //一些必输项自动赋值
            strPKValue = DateTime.Now.ToString("yyyyMMdd") + GetMaxLs(DateTime.Now.ToString("yyyyMMdd"), strTableName, "SerialNum", 4).ToString("0000");
            if (dsGetData.Tables[strTableName].Columns.Contains("SaveTime"))
                dsGetData.Tables[strTableName].DefaultView[0]["SaveTime"] = DateTime.Now.ToString();
            dsGetData.Tables[strTableName].DefaultView[0]["SerialNum"] = strPKValue;
            dsGetData.Tables[strTableName].DefaultView[0]["CreateTime"] = DateTime.Now.ToString();
            dsGetData.Tables[strTableName].DefaultView[0]["ISDel"] = 0;
            dsGetData.Tables[strTableName].DefaultView[0]["UserCode"] = userCode;
            dsGetData.Tables[strTableName].DefaultView[0].EndEdit();
            #endregion
            #region 细表部分
            // 先删除细表数据
            string cInvList = "";
            JavaScriptSerializer SerializerDetail = new JavaScriptSerializer();
            dynamic ListDsDataDetail = Serializer.Deserialize<dynamic>(DetailList);
            for (int i = 0; i < ListDsDataDetail.Length; i++)
            {
                DataRow drDetailNew = dsGetData.Tables[strTableDetail].NewRow();
                dynamic dtmtsavelist = ListDsDataDetail[i];
                foreach (dynamic dsv in dtmtsavelist)
                {
                    String strDetaliTablename = string.Empty;
                    String strDetaliCoulumName = string.Empty;
                    String strDetaliCoulunValue = string.Empty;
                    foreach (string strkey in dsv.Keys)
                    {
                        if (strkey == "TableName")
                            strDetaliTablename = dsv[strkey].ToString();
                        if (strkey == "CoulumName")
                            strDetaliCoulumName = dsv[strkey].ToString();
                        if (strkey == "CoulunValue")
                            strDetaliCoulunValue = dsv[strkey].ToString();
                    }
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        continue;
                    //
                    if (!dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].ReadOnly && strDetaliCoulumName != "SortID" && strDetaliCoulumName != "ISDel")
                    {
                        if (dsGetData.Tables[strDetaliTablename].Columns.Contains(strDetaliCoulumName))
                        {
                            if (strDetaliCoulunValue == null || strDetaliCoulunValue == string.Empty)
                                continue;
                            if (dsGetData.Tables[strDetaliTablename].Columns[strDetaliCoulumName].DataType.Name == "Int32")
                            {
                                decimal dec = Convert.ToDecimal(strDetaliCoulunValue);
                                drDetailNew[strDetaliCoulumName] = Convert.ToInt32(dec);
                            }
                            else
                            {
                                drDetailNew[strDetaliCoulumName] = strDetaliCoulunValue;
                            }
                        }
                    }
                }
                //赋值一些必要的值
                drDetailNew["SerialNum"] = strPKValue;
                drDetailNew["ISDel"] = 0;
                drDetailNew["SortID"] = i;
                drDetailNew["Qty"] = 1;
                drDetailNew["KCQty"] = 0;
                if (drDetailNew["cWhCode"].ToString() == "") drDetailNew["cWhCode"] = "003";
                if (drDetailNew["cWhCode"].ToString() == "003")
                    drDetailNew["cWhName"] = "成品仓";
                else if (drDetailNew["cWhCode"].ToString() == "004")
                    drDetailNew["cWhName"] = "售后仓";
                else
                    drDetailNew["cWhName"] = "半成品仓";
                drDetailNew.EndEdit();
                if (cInvList != "") cInvList += ",";
                cInvList += "'" + drDetailNew["cInvCode"].ToString() + "'";
                dsGetData.Tables[strTableDetail].Rows.Add(drDetailNew);
            }
            #endregion
            string sql = "select a.*,b.cInvName from " + Common.GetdatabaseName("") + ".dbo.ST_SNState a left join V_YY_inventory b on a.cInvCode=b.cInvCode where iSNState=2 and a.cInvCode in (" + cInvList + ")";
            DataSet dss = new DataSet();
            try
            {
                dss = CustomizableDesignBLL.GetData(sql);
            }
            catch (Exception ex)
            {
                damResult.message = "获取序列号状态失败：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            foreach (DataRowView drv in dss.Tables[0].DefaultView)
            {
                string cInvSN = drv["cInvSN"].ToString();
                bool flag = false;
                foreach (DataRowView drw in dsGetData.Tables[1].DefaultView)
                {
                    if (drw["XLCode"].ToString() == cInvSN)
                    {
                        drw["KCQty"] = 1;
                        drw.EndEdit();
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    //DataRow drDetailNew = dsGetData.Tables[strTableDetail].NewRow();
                    //drDetailNew["SerialNum"] = strPKValue;
                    //drDetailNew["ISDel"] = 0;
                    //drDetailNew["Qty"] = 0;
                    //drDetailNew["KCQty"] = 1;
                    //drDetailNew["XLCode"] = cInvSN;
                    //drDetailNew["cInvCode"] = drv["cInvCode"].ToString();
                    //drDetailNew["cInvName"] = drv["cInvName"].ToString();
                    //drDetailNew["iSNState"] = drv["iSNState"].ToString();
                    //drDetailNew["cBatch"] = drv["cBatch"].ToString();
                    //drDetailNew["cWhCode"] = drv["cWhCode"].ToString();
                    //if (drDetailNew["cWhCode"].ToString() == "") drDetailNew["cWhCode"] = "003";
                    //if (drDetailNew["cWhCode"].ToString() == "003")
                    //    drDetailNew["cWhName"] = "成品仓";
                    //else if (drDetailNew["cWhCode"].ToString() == "004")
                    //    drDetailNew["cWhName"] = "售后仓";
                    //else
                    //    drDetailNew["cWhName"] = "半成品仓";
                    //drDetailNew.EndEdit();
                    //dsGetData.Tables[strTableDetail].Rows.Add(drDetailNew);
                }
            }
            foreach (DataRowView d in dsGetData.Tables[strTableDetail].DefaultView)
            {
                decimal qty = decimal.Parse(d["Qty"].ToString());
                decimal kcqty = decimal.Parse(d["KCQty"].ToString());
                if (qty == kcqty) d["type"] = "正常";
                else if (qty < kcqty) d["type"] = "盘亏";
                else d["type"] = "盘盈";
                d.EndEdit();
            }
            try
            {
                CustomizableDesignBLL.SaveData(dsGetData, dtnGetDataList);
            }
            catch (Exception ex)
            {
                damResult.message = "保存模块数据报错：" + ex.Message;
                jsonResult = JsonConvert.SerializeObject(damResult);
                return jsonResult;
            }
            damResult.success = true;
            damResult.message = strPKValue;
            jsonResult = JsonConvert.SerializeObject(damResult);
            return jsonResult;
        }
    }
}
